<template>
  <div>
    <!--  面包屑导航区-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>分类管理</el-breadcrumb-item>
    <el-breadcrumb-item>分类列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!--  卡片视图区-->
  <el-card>
<!--    搜索与添加区域-->

    <el-row :gutter="20">
      <el-col :span="12">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getCateList">
          <el-button slot="append" icon="el-icon-search" @click="searchCate"></el-button>
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="addDialogVisible = true">添加分类</el-button>
      </el-col>
    </el-row>
    <el-table :data="cateList" border stripe>
      <el-table-column label="ID" type="index"></el-table-column>
      <el-table-column label="分类名称" prop="name"></el-table-column>
      <el-table-column label="分类描述" prop="categoryDesc"></el-table-column>
      <el-table-column label="是否显示">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status" @change="cateStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120px">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCate(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[1, 2, 4, 5]"
      :page-size="this.queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.total">
    </el-pagination>
  </el-card>

 <!-- 添加分类对话框 -->
  <el-dialog
    title="添加分类"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed">
<!--    内容主体区域-->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="addForm.name"></el-input>
      </el-form-item>
      <el-form-item label="分类描述" prop="categoryDesc">
        <el-input v-model="addForm.categoryDesc"></el-input>
      </el-form-item>
    </el-form>
   <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addCate">确 定</el-button>
    </span>
  </el-dialog>

  <!--修改分类对话框-->
  <el-dialog
    title="修改分类信息"
    :visible.sync="editDialogVisible"
    width="50%"
  @close="editDialogClosed">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="editForm.name" disabled></el-input>
      </el-form-item>
      <el-form-item label="分类描述" prop="categoryDesc">
        <el-input v-model="editForm.categoryDesc"></el-input>
      </el-form-item>
      
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editCate(editForm)">确 定</el-button>
  </span>
  </el-dialog>
  </div>
</template>

<script>
export default {
    name: 'Cate',
    data() {
      return {
        queryInfo: {
          // query: '',
          pagenum: 1,
          pagesize: 2
        },
        cateList: [],
        total: 0,

        //控制添加分类时弹出框显示与隐藏的标志
        addDialogVisible: false,
        //添加分类的表单数据
        addForm: {
          name: '',
          categoryDesc: ''
        },
        //添加分类时的验证规则对象
        addFormRules: {
          name: [
            { required: true, message: '请输入分类名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度应在 3 到 9 个字符', trigger: 'blur' }
          ],
          categoryDesc: [
            { required: true, message: '请输入分类描述', trigger: 'blur' },
            { min: 3, max: 10, message: '长度应在 3 到 10 个字符', trigger: 'blur' }
          ]
        },

        //控制编辑分类对话框的显示与隐藏
        editDialogVisible: false,
        //编辑分类的表单对象
        editForm: {
        },
        //编辑分类时的验证规则对象
        editFormRules: {
          categoryDesc: [
            { required: true, message: '请输入分类描述', trigger: 'blur' },
            { min: 3, max: 10, message: '长度应在 3 到 10 个字符', trigger: 'blur' }
          ]
        }
      }
    },
    //生命周期函数
    created() {
      this.getCateList();
    },
    methods: {
      // 获取分类列表
      async getCateList() {
        this.cateList = [];
        const {data: res} = await this.$http.get('cate/list', {params:this.queryInfo});
        console.log(res)
        if (res.status !== 200) {
          return this.$message.error('获取分类列表失败')
        }
        // 将分类状态由0、1改为ture、false
        res.page.records.forEach((v,i)=>{
          if(v.status === 0) {
            v.status = true
            this.cateList.push(v)
          }else {
            v.status = false
            this.cateList.push(v)
          }
        });
        this.cateList = res.page.records;
        this.total = res.page.total;
      },
      //监听 pagesize 改变事件
      handleSizeChange(newSize) {
        // console.log(newSize);
        this.queryInfo.pagesize = newSize;
        this.getCateList();
      },
      //监听 currentPage 改变事件
      handleCurrentChange(newPage) {
        // console.log(newPage);
        this.queryInfo.pagenum = newPage;
        this.getCateList();
      },
    //  监听分类状态的改变事件
      async cateStatusChange(cateInfo) {
        console.log(cateInfo)
        const {data: res} = await this.$http.post(`cate/status?id=${cateInfo.id}`);
        if (res.status == 200) {
          cateInfo.status = !cateInfo.status;
          return this.$message.error('分类状态修改失败');
        }
        return this.$message.success('分类状态修改成功')
      },
      //搜索分类
      searchCate() {
        this.getCateList();
      },
      //监听添加分类对话框的关闭事件,关闭时重置addForm的内容
      addDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },
      //添加分类
      addCate() {
        this.$refs.addFormRef.validate(async vaild => {
          // console.log(vaild);
          if (!vaild) return;
          const {data: res} = await this.$http.post('cate/add', this.addForm);
          // console.log(res);
          if (res.status !== 200) return this.$message.error('添加分类失败');
          this.$message.success('添加分类成功');
          this.addDialogVisible = false;
          this.getCateList();
        })
      },
      //监听修改分类对话框的关闭事件,关闭时重置editForm的内容
      editDialogClosed() {
        this.$refs.editFormRef.resetFields();
      },
      //显示修改分类对话框，并根据id显示被修改的分类信息
      async showEditDialog(id) {
        this.editDialogVisible = true;
        const {data: res} = await this.$http.get(`cate/getCateById/${id}`)
        if (res.status !== 200) return this.$message.error('获取分类信息失败！');
        this.editForm = res.data;
        console.log(this.editForm)
      },
      //提交修改后的分类信息
      editCate(editForm) {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return;
          const {data: res} = await this.$http.post(`cate/update`, editForm);
          if (res.status !== 200) return this.$message.error('更新失败');
          this.$message.success('更新成功');
          this.editDialogVisible = false;
          this.getCateList();
        })
      },
      //  根据id删除分类
      async removeCate(id) {
        const confirmRes = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        //如果确认删除，则confirmRes的返回值为 confirm
        //如果取消删除，则confirmRes的返回值为 cancel
        if (confirmRes === 'cancel') return this.$message.info('已取消删除');
        const {data: res} = await this.$http.post(`cate/delete?id=${id}`);
        if (res.status !== 200) return this.$message.error('删除失败');
        this.getCateList();
        this.$message.success('删除成功');
      }
    }
  }
</script>

<style>

</style>